package com.mars.upms.web.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mars.base.common.base.BaseController;
import com.mars.base.common.base.BaseResult;
import com.mars.base.common.exception.AppException;
import com.mars.base.common.utils.IpHelper;
import com.mars.base.common.utils.Paginator;
import com.mars.logger.annotation.Log;
import com.mars.logger.enums.ActionType;
import com.mars.upms.dto.UpmsUserDto;
import com.mars.upms.entity.UpmsUser;
import com.mars.upms.rpc.api.UpmsUserService;

@RestController
@RequestMapping(value = "/api/upms/user")
public class UpmsUserController extends BaseController {

	@Autowired
	private UpmsUserService upmsUserService;

	@PostMapping(value = "/add")
	public Object add(@RequestBody UpmsUser entity) {
		try {
			if (StringUtils.isBlank(entity.getAccount())) {
				return BaseResult.failure("账号不能为空");
			}
			if (StringUtils.isBlank(entity.getEmail())) {
				return BaseResult.failure("邮件地址不能为空");
			}
			if (StringUtils.isBlank(entity.getMobile())) {
				return BaseResult.failure("手机号码不能为空");
			}
			if (null != this.upmsUserService.checkValue("account", entity.getAccount())) {
				return BaseResult.failure("账号已存在");
			}
			if (null != this.upmsUserService.checkValue("email", entity.getEmail())) {
				return BaseResult.failure("邮件地址已存在");
			}
			if (null != this.upmsUserService.checkValue("mobile", entity.getMobile())) {
				return BaseResult.failure("手机号码已存在");
			}
			
			this.upmsUserService.insertSelective(entity);
			
			return BaseResult.ok();
		} catch (AppException e) {
			throw e;
		}
	}

	@GetMapping(value = "/delete/{id}/{isAdmin}")
	public Object delete(@PathVariable Integer id, @PathVariable Integer isAdmin) {
		try {
			if(isAdmin == 1) {
				return BaseResult.build(false, "该用户类型为【超级管理员】，不能删除.") ;
			}
			this.upmsUserService.delete(id);
			return BaseResult.ok();
		} catch (AppException e) {
			throw e;
		}
	}

	@PostMapping(value = "/update")
	public Object update(@RequestBody UpmsUser entity) {
		try {
			if (StringUtils.isBlank(entity.getAccount())) {
				return BaseResult.failure("账号不能为空");
			}
			if (StringUtils.isBlank(entity.getEmail())) {
				return BaseResult.failure("邮件地址不能为空");
			}
			if (StringUtils.isBlank(entity.getMobile())) {
				return BaseResult.failure("手机号码不能为空");
			}
			
			UpmsUser oldUser = this.upmsUserService.selectById(entity.getId()) ;
			if(null != oldUser.getAccount() && !oldUser.getAccount().equals(entity.getAccount())) {
				if(null != this.upmsUserService.checkValue("account", entity.getAccount())) {
					return BaseResult.failure("账号已存在");
				}
			}
			if(null != oldUser.getEmail() && !oldUser.getEmail().equals(entity.getEmail())) {
				if(null != this.upmsUserService.checkValue("email", entity.getEmail())) {
					return BaseResult.failure("邮件地址已存在");
				}
			}
			if(null != oldUser.getMobile() && !oldUser.getMobile().equals(entity.getMobile())) {
				if(null != this.upmsUserService.checkValue("mobile", entity.getMobile())) {
					return BaseResult.failure("手机号码已存在");
				}
			}
			
			this.upmsUserService.updateSelective(entity);

			return BaseResult.ok();
		} catch (AppException e) {
			throw e;
		}
	}

	@GetMapping(value = "/get/{id}")
	public Object list(@PathVariable Integer id) {
		return this.upmsUserService.selectById(id);
	}
	
	@GetMapping(value = "/list")
	public Object list(UpmsUserDto dto) {
		return this.upmsUserService.selectPage(new Paginator(this.request), dto);
	}
	

	@Log(actionType=ActionType.BUSINESS, description="修改个人密码")
	@PostMapping(value = "/updatePassword")
	public Object updatePassword(@RequestBody UpmsUserDto dto) {
		try {
			if(StringUtils.isBlank(dto.getOldPassword())) {
				return BaseResult.failure("原密码不能为空");
			}
			if(StringUtils.isBlank(dto.getNewPassword())) {
				return BaseResult.failure("新密码不能为空");
			}
			this.upmsUserService.updatePassword(dto.getId(), dto.getOldPassword(), dto.getNewPassword()) ;
			return BaseResult.ok();
		} catch (RuntimeException e) {
			return BaseResult.failure(e.getMessage());
		}
	}
	
	@PostMapping(value = "/getAccount")
	public Object getAccount(String account) {
		return this.upmsUserService.getAccount(account);
	}
	
	@GetMapping(value = "/getUserDetail")
	public Object getUserDetail(UpmsUserDto dto) {
		return this.upmsUserService.getUserDetail(dto);
	}
	
	@Log(actionType=ActionType.BUSINESS, description="重置密码")
	@PostMapping(value = "/batchResetPassword")
	public Object batchResetPassword(@RequestBody List<Integer> ids) {
		this.upmsUserService.batchResetPassword(ids.toArray(new Integer[ids.size()]));
		
		return BaseResult.ok();
	}

	@Log(actionType=ActionType.BUSINESS, description="批量修改用户状态")
	@PostMapping(value = "/batchUpdateStatus")
	public Object batchUpdateStatus(@RequestBody Map<Object, Object> params) {
		JSONArray parseArray = JSON.parseArray(params.get("ids").toString());
		Integer[] ids = parseArray.toArray(new Integer[parseArray.size()]);
		Integer status = (Integer) params.get("status");
		if(null != ids && ids.length > 0) {
			this.upmsUserService.batchUpdateStatus(ids, status);
		} else {
			return BaseResult.failure("请选择需要设置的记录");
		}
		
		return BaseResult.ok();
	}
	
	@Log(actionType=ActionType.BUSINESS, description="添加用户到用户组")
	@PostMapping(value = "/addUserToGroupAssign")
	public Object addUserToGroupAssign(@RequestBody UpmsUserDto dto) {
		try {
			if(null == dto.getUserIds() || dto.getUserIds().isEmpty()) {
				return BaseResult.failure("请选择需要加入组的用户");
			}
			this.upmsUserService.addUsersToGroupAssign(dto);
			return BaseResult.ok();
		} catch (AppException e) {
			throw e;
		}
	}
	
	@Log(actionType=ActionType.BUSINESS, description="添加用户到组织机构")
	@PostMapping(value = "/addUserToCompanyDeptAssign")
	public Object addUserToOrganizationAssign(@RequestBody UpmsUserDto dto) {
		try {
			if(null == dto.getUserIds() || dto.getUserIds().isEmpty()) {
				return BaseResult.failure("请选择需要加入组织机构的用户");
			}
			this.upmsUserService.addUsersToCompanyDeptAssign(dto);
			return BaseResult.ok();
		} catch (AppException e) {
			throw e;
		}
	}
	
	@Log(actionType=ActionType.BUSINESS, description="添加用户到角色")
	@PostMapping(value = "/addUserToRoleAssign")
	public Object addUserToRoleAssign(@RequestBody UpmsUserDto dto) {
		try {
			if(null == dto.getUserIds() || dto.getUserIds().isEmpty()) {
				return BaseResult.failure("请选择需要加入分配的用户");
			}
			this.upmsUserService.addUsersToRoleAssign(dto);
			return BaseResult.ok();
		} catch (AppException e) {
			throw e;
		}
	}
	
	@GetMapping(value = "/getUserIpCity")
	public Object getUserIpCity(String ip) {
		if(ip.equals("127.0.0.1")) {
			return null;
		} else {
			return IpHelper.getIpCity(ip) ;
		}
	}
}
